package com.chhuang.ewcrm.ctrl;

import com.browniebytes.javafx.control.DateTimePicker;
import com.chhuang.ewcrm.App;
import com.chhuang.ewcrm.api.AppRequest;
import com.chhuang.ewcrm.api.ServiceRxSchedulers;
import com.chhuang.ewcrm.api.ServiceSubscriber;
import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.bean.TableColumnBean;
import com.chhuang.ewcrm.cons.Constants;
import com.chhuang.ewcrm.dao.WMenuDao;
import com.chhuang.ewcrm.dao.WUserMenuDao;
import com.chhuang.ewcrm.date.DateUtil;
import com.chhuang.ewcrm.entity.*;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.utils.MyAlert;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jfoenix.controls.JFXButton;
import com.jfoenix.controls.JFXCheckBox;
import javafx.beans.property.ObjectProperty;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URL;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.ResourceBundle;

import static javafx.application.Platform.runLater;

/**
 * 过磅人员信息维护，包括基本信息 和 菜单权限， 基本信息在服务器上，菜单权限在本地数据库
 */
public class WeigherController implements InitController{
    private final Logger logger = LoggerFactory.getLogger(WeigherController.class);

    @FXML
    private TextField usernameTextField;
    @FXML
    private TextField fullnameTextField;
    @FXML
    private TextField userphoneTextField;
    @FXML
    private TextField usersphoneTextField;
    @FXML
    private TextField emailTextField;
    @FXML
    private FlowPane menusFlowPane;
    private ObservableList<Node> nodes;
    @FXML
    private JFXButton saveJFXButton;
    @FXML
    private TextField queryUsernameTextField;
    @FXML
    private TextField queryFullnameField;
    @FXML
    private TextField queryUserphoneTextField;
    @FXML
    private TextField queryUsersphoneTextField;
    @FXML
    private TextField queryEmailTextField;
    @FXML
    private DateTimePicker createTimeStartPicker;
    private ObjectProperty<LocalDateTime> createTimeStart;
    @FXML
    private DateTimePicker createTimeEndPicker;
    private ObjectProperty<LocalDateTime> createTimeEnd;
    @FXML
    private JFXButton seachJFXButton;
    @FXML
    private TableView<SysUser> tableView;
    @FXML
    private ChoiceBox<Integer> pageSizeChiceBox;
    @FXML
    private Label pagesLabel;
    @FXML
    private Label totalLabel;
    @FXML
    private Pagination pagination;

    private SysUser selectedUser = null;
    private final QueryBean<SysUser> queryBean = new QueryBean<>();

    private final WMenuDao wMenuDao = App.getSession().getMapper(WMenuDao.class);
    private final WUserMenuDao wUserMenuDao = App.getSession().getMapper(WUserMenuDao.class);

    private TableColumnBean[] tableColumnBeans = {
            new TableColumnBean("USERID","userId",false, false),
            new TableColumnBean("用户名","username",true),
            new TableColumnBean("姓名","fullname",true),
            new TableColumnBean("手机号","userphone",true),
            new TableColumnBean("短号","usersphone",true),
            new TableColumnBean("邮箱","email",true),
            new TableColumnBean("头像","userphoto",false),
            new TableColumnBean("角色","roleName",true),
            new TableColumnBean("状态","status",true){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    Integer status = (Integer)o;
                    switch (status){
                        case 1: return "正常";
                        default: return "未知";
                    }
                }
            },
            new TableColumnBean("最后登录时间","lastLoginTime",true,false){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.YYYY_MM_DD_HH_MM_SS);
                }
            },
            new TableColumnBean("创建时间","createTime",true,false){
                @Override
                public String format(Object o) {
                    if(o==null) return null;
                    return DateUtil.date2String((Date)o, DateUtil.YYYY_MM_DD_HH_MM_SS);
                }
            }
    };

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        initTable();
        initMenus();
        initDateTimePicker();
        initListener();
    }

    private void initListener() {
        //每页显示多少条数据选择器监听
        pageSizeChiceBox.getSelectionModel().selectedItemProperty().addListener((observableValue, integer, t1) -> {
            queryBean.setPageSize(t1);
            getTableData();
        });

        //点击分页按钮监听
        pagination.currentPageIndexProperty().addListener((observableValue, number, t1) -> {
            queryBean.setPageNum(t1.intValue()+1);
            getTableData();
        });

        //点击保存
        saveJFXButton.setOnAction(event -> {
            if(selectedUser==null){
                MyAlert.showAlert("提示","没有选中要修改的过磅员","请先双击表格中某一行要修改的过磅员");
                return;
            }
            if(nodes!=null && !nodes.isEmpty()) {
                WUserMenu wum = new WUserMenu();
                wum.setUserId(selectedUser.getUserId());
                wUserMenuDao.deleteByEntity(wum);

                List<WUserMenu> wUserMenuList = new LinkedList<>();
                for(Node item : nodes){
                    JFXCheckBox checkBox = (JFXCheckBox) item;
                    if (checkBox.isSelected()) {
                        String menuId = checkBox.getId();
                        WMenu wMenu = wMenuDao.queryById(menuId);
                        if (wMenu != null) {
                            WUserMenu wUserMenu = new WUserMenu();
                            wUserMenu.setUserId(selectedUser.getUserId());
                            wUserMenu.setMenuId(wMenu.getMenuId());
                            wUserMenu.setMenuName(wMenu.getMenuName());
                            wUserMenu.setFxmlUrl(wMenu.getFxmlUrl());
                            wUserMenu.setParentMenuId(wMenu.getParentMenuId());
                            Date now = new Date();
                            wUserMenu.setCreateTime(now);
                            wUserMenu.setModifyTime(now);
                            wUserMenuList.add(wUserMenu);
                        }
                    }
                }
                if(!wUserMenuList.isEmpty()) wUserMenuDao.insertBatch(wUserMenuList);

                MyAlert.showAlertLater("成功","过磅人员信息维护完成","");
            }
        });

        //查询
        seachJFXButton.setOnAction(event -> {
            SysUser searchUser = new SysUser();
            searchUser.setUsername(queryUsernameTextField.getText());
            searchUser.setFullname(queryFullnameField.getText());
            searchUser.setUserphone(queryUserphoneTextField.getText());
            searchUser.setUsersphone(queryUsersphoneTextField.getText());
            searchUser.setEmail(queryEmailTextField.getText());
            if(!createTimeStartPicker.isVoid())
                searchUser.setCreateTimeStart(DateUtil.localDateTime2Date(createTimeStart.get()));
            if(!createTimeEndPicker.isVoid())
                searchUser.setCreateTimeEnd(DateUtil.localDateTime2Date(createTimeEnd.get()));
            queryBean.setQuery(searchUser);
            getTableData();
        });
    }

    private void initDateTimePicker() {
        createTimeStartPicker.setPopupPreWidth(createTimeStartPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        createTimeStart = createTimeStartPicker.dateTimeProperty();
        createTimeEndPicker.setPopupPreWidth(createTimeEndPicker.getPrefWidth());//设置下拉选择框宽度和日期输入框一样
        createTimeEnd = createTimeEndPicker.dateTimeProperty();
    }

    private void initMenus() {
        PageHelper.orderBy("create_time");
        List<WMenu> menus = wMenuDao.query(null);
        if(menus!=null && !menus.isEmpty()){
            nodes = menusFlowPane.getChildren();
            menus.forEach(item->{
                JFXCheckBox jfxCheckBox = new JFXCheckBox(item.getMenuName());
                jfxCheckBox.setId(item.getMenuId());
                if("/fxml/weigh.fxml".equals(item.getFxmlUrl()) ||
                    "/fxml/report.fxml".equals(item.getFxmlUrl())||
                    "/fxml/weighTemp.fxml".equals(item.getFxmlUrl())){
                    jfxCheckBox.setSelected(true);
                    jfxCheckBox.setDisable(true);
                    jfxCheckBox.setDisableVisualFocus(true);
                }
                nodes.add(jfxCheckBox);
            });
        }
    }

    private void initTable() {
        //设置列
        List<TableColumn<SysUser, Object>> tableColumns = new LinkedList<>();
        for (TableColumnBean tcb : tableColumnBeans){
            TableColumn<SysUser, Object> tableColumn = new TableColumn<>(tcb.getColumnName());
            tableColumn.setCellValueFactory(new PropertyValueFactory<>(tcb.getRecordName()));
            tableColumn.setSortable(tcb.isSort());
            tableColumn.setVisible(tcb.isVisible());
            tableColumn.setCellFactory(eBuyObjectTableColumn -> {
                TableCell<SysUser, Object> cell = new TableCell<>(){
                    @Override
                    protected void updateItem(Object o, boolean b) {
                        super.updateItem(o, b);
                        if(b || o==null){
                            this.setText(null);
                        }else {
                            this.setText(tcb.format(o));
                        }
                    }
                };
                cell.setAlignment(Pos.CENTER);
                return cell;
            });
            tableColumns.add(tableColumn);
        }
        tableView.getColumns().addAll(tableColumns);//添加列

        //设置双击某一列
        tableView.setRowFactory(tableView -> {
            TableRow<SysUser> row = new TableRow<>();
            row.setOnMouseClicked(mouseEvent -> {
                if(mouseEvent.getClickCount()==2 && !row.isEmpty()){
                    selectedUser = row.getItem();
                    autoForm(selectedUser);
                }
            });
            return row;
        });

        tableView.setSortPolicy(tableView -> {
            ObservableList<TableColumn<SysUser,?>> list = tableView.getSortOrder();
            if(list!=null && !list.isEmpty()){
                String orderby = "";
                for (TableColumn<SysUser,?> tableColumn: list){
                    String property = ((PropertyValueFactory)tableColumn.getCellValueFactory()).getProperty();
                    TableColumn.SortType sortType = tableColumn.getSortType();
                    if(sortType == TableColumn.SortType.DESCENDING) property += " desc";
                    orderby += property+",";
                }
                orderby = orderby.substring(0, orderby.length()-1);
                if(StringUtils.isNotEmpty(orderby)) queryBean.setOrderBy(orderby);
                getTableData();
            }
            return true;
        });

        //每页显示多少条数据
        pageSizeChiceBox.getItems().addAll(5,10,20,50,100,150,200);
        pageSizeChiceBox.setValue(queryBean.getPageSize());

        pagination.setMaxPageIndicatorCount(9);//数字按钮数量

        //获取表格数据
        getTableData();
    }

    private void autoForm(SysUser selectedUser) {
        if(selectedUser==null) return;
        usernameTextField.setText(selectedUser.getUsername());
        fullnameTextField.setText(selectedUser.getFullname());
        userphoneTextField.setText(selectedUser.getUserphone());
        usersphoneTextField.setText(selectedUser.getUsersphone());
        emailTextField.setText(selectedUser.getEmail());
        //获取选择中菜单
        WUserMenu temp = new WUserMenu();
        temp.setUserId(selectedUser.getUserId());
        List<WUserMenu> wUserMenus = wUserMenuDao.query(temp);
        if(wUserMenus!=null && !wUserMenus.isEmpty() && nodes!=null && !nodes.isEmpty()){
            nodes.forEach(node -> {
                ((JFXCheckBox) node).setSelected(false);
                wUserMenus.forEach(item -> {
                    if (item.getMenuId().equals(node.getId())) {
                        ((JFXCheckBox) node).setSelected(true);
                        return;
                    }
                });
            });
        }
    }

    private void getTableData() {
        if(StringUtils.isEmpty(queryBean.getOrderBy())){
            queryBean.setOrderBy("create_time");
        }
        AppRequest.getInstance().getService().getWeighers(queryBean)
                .compose(ServiceRxSchedulers.compose())
                .subscribe(new ServiceSubscriber<>("获取过磅员列表") {
                    @Override
                    protected void onHandleSuccess(PageInfo<SysUser> pageInfo) {
                        runLater(()->{
                            //总页数发生改变时从第一页开始
                            if(queryBean.getPageNum()>pageInfo.getPages() && queryBean.getPageNum()!=1 ){
                                queryBean.setPageNum(1);
                                getTableData();
                                return;
                            }

                            //一共多少条数据
                            if(queryBean.getTotal()-pageInfo.getTotal()!=0){
                                queryBean.setTotal(pageInfo.getTotal());
                                totalLabel.setText(String.valueOf(queryBean.getTotal()));
                            }

                            //一共多少页
                            if(queryBean.getPages()-pageInfo.getPages()!=0) {
                                queryBean.setPages(pageInfo.getPages());
                                pagesLabel.setText(String.valueOf(queryBean.getPages()));
                                pagination.setPageCount(queryBean.getPages());
                            }

                            tableView.getItems().clear();
                            if(pageInfo.getList()!=null && !pageInfo.getList().isEmpty())
                                tableView.getItems().addAll(pageInfo.getList());
                        });
                    }
                });
    }

    @Override
    public void close() {

    }
}
